package pers.hll.aigc4chat.server.handler;

import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import pers.hll.aigc4chat.protocol.wechat.response.webwxsync.AddMsg;
import pers.hll.aigc4chat.server.entity.WeChatMessage;
import pers.hll.aigc4chat.server.service.IWeChatApiService;
import pers.hll.aigc4chat.server.service.IWeChatMessageService;
import pers.lys.aigc4chat.model.baidu.BaiduApi;
import pers.lys.aigc4chat.model.baidu.constant.ModelName;
import pers.lys.aigc4chat.model.baidu.constant.Role;
import pers.lys.aigc4chat.model.baidu.request.body.ChatReqBody;
import pers.lys.aigc4chat.model.baidu.request.body.Message;
import pers.lys.aigc4chat.model.baidu.response.body.ChatRespBody;

import java.util.List;
import java.util.function.Function;

/**
 * 消息处理器
 *
 * @author hll
 * @since 2024/05/07
 */
@RequiredArgsConstructor
@Component(MessageHandlerName.BAIDU_MESSAGE_HANDLER)
public class BaiduMessageHandler implements MessageHandler {

    private final IWeChatApiService weChatApiService;

    private final IWeChatMessageService weChatMessageService;

    @Override
    public void handle(AddMsg addMsg) {
        ChatReqBody chatReqBody = new ChatReqBody();
        List<WeChatMessage> weChatMessages = weChatMessageService.listChatHistoryForModel(addMsg.getFromUserName(), 10);
        chatReqBody.setMessages(converter(weChatMessages, addMsg.getFromUserName()));
        ChatRespBody chat = BaiduApi.chat(chatReqBody, ModelName.EB_INSTANT);
        weChatApiService.sendTextMessage(chat.getResult(), addMsg.getFromUserName());
    }

    private List<Message> converter(List<WeChatMessage> weChatMessages, String userName) {
        Function<WeChatMessage, Message> messageFunction = x ->
            new Message(StringUtils.equals(x.getFromUserName(), userName) ? Role.USER : Role.ASSISTANT, x.getContent());
        return weChatMessages.stream()
                .map(messageFunction)
                .toList();
    }
}
